<template>
  <div class="write" style="height: 100%;margin-top: 0;padding: 0 5px" v-show="isEnd">
    <!-- form 表单-->
    <Write ref="write" :senderEmail="form.senderEmail" @getSendEmail="getSendEmail" @review="review"
           :isLoading="isLoading"
           :emailSubject="form.emailSubject" @getInfoWrite="getInfoWrite" @getCancel="getCancel"
           @toApproval="toApproval"></Write>
    <!-- 编辑器操作-->
    <MakeBtn ref="makeBtn" @getInfoMake="getInfoMake"></MakeBtn>
    <!--发件人信息-->
    <div class="info">
      <h1>发件人: {{form.senderNickName}}&nbsp;&nbsp; {{form.senderEmail}}
      </h1>
      <el-checkbox-group v-model="checkList">
        <el-checkbox label="紧急"></el-checkbox>
        <el-checkbox label="回执"></el-checkbox>
        <el-checkbox label="定时发送"></el-checkbox>
        <el-checkbox label="追踪邮件"></el-checkbox>
      </el-checkbox-group>
    </div>
    <!--操作按钮-->
    <div class="make-btn">
      <el-button class="active" @click="$refs.write.sendEmail('')" :disabled="isLoading"><i
        class="icon-fasong iconfont"></i>发送
      </el-button>
      <el-button @click="$refs.write.toApproval()" :disabled="isLoading">提交审批</el-button>
      <el-button @click="$refs.write.sendEmail(2)" :disabled="isLoading">{{content?'保存至草稿箱':'存草稿'}}</el-button>
    </div>
    <DialogTargetTime ref="dialogTargetTime" @getRightTime="getRightTime"></DialogTargetTime>
    <DialogApproval ref="dialogApproval" @reset="reset"></DialogApproval>
  </div>
</template>
<script>
    import DialogTargetTime from '@/components/mail/DialogTargetTime'
    import DialogApproval from '@/components/mail/DialogApproval'
    import Write from '@/components/mail/write/Write'
    import MakeBtn from '@/components/mail/write/MakeBtn'
    import {sendEmail} from "@/api/mail/write"
    import {dealStr} from '@/util/util'
    import {mapGetters, mapState} from "vuex"

    export default {
        name: 'write',
        props: ['content', 'model', 'mailbox'],
        components: {Write, MakeBtn, DialogTargetTime, DialogApproval},
        data() {
            return {
                isLoading: false,
                form: {
                    addresseeEmail: [],//收件人邮箱数组
                    emailCarbonCopy: [],//抄送数组
                    emailSecretDelivery: [],//密送数组
                    emailHtmlpicList: [],//附件列表
                    emailSubject: '',//主题
                    emailContent: '',//邮件内容
                    emailReceipt: 0,//是否回执 0-默认不回执，1-回执
                    emaileDelivery: 0,//投递状态  （紧急与非紧急） 0-默认常规，2-紧急
                    monocular: 0,//群发单显
                    emailTrack: 0,//0 - 不追踪  1 - 追踪
                    emailSendTiming: '', //邮件定时发送时间
                    senderEmail: '',//发件人邮箱
                    senderNickName: '',//发件人昵称
                    boxId: '',
                    emailOriginalId: ''
                },
                pickerOptions: {
                    disabledDate: time => {
                        return time.getTime() < Date.now() - 8.64e7
                    }
                },
                checkList: ['追踪邮件'],
                isEnd: false
            }
        },
        computed: {
            ...mapState(['common']),
            ...mapGetters(["userInfo"]),
        },
        watch: {
            checkList(val, old) {
                let el = this.getArrDifference(val, old);
                if (el[0] == '定时发送') {
                    if (!old.includes('定时发送')) {
                        this.$refs.dialogTargetTime.init();
                    } else {
                        this.form.emailSendTiming = '';
                    }
                }
            }
        },
        mounted() {
            this.bus.$on('getInfoWrite', params => {
                this.form = Object.assign({}, this.form, params);
                this.bus.$off('getInfoWrite');
                //收件人，主题，发件人
                if (this.form.addresseeEmail.length != 0 && this.form.emailSubject != '' && (this.form.senderEmail != '') && !this.common.isExpired) {
                    this.$confirm(' <div style="margin: 20px 10px;">\n' +
                        '        <p style="line-height: 30px;\n' +
                        '        font-size: 14px;">您正在编辑内容，是否保存至草稿箱？</p>\n' +
                        '      </div>', '保存邮件到草稿箱', {
                        dangerouslyUseHTMLString: true,
                        closeOnClickModal: false,
                        closeOnPressEscape: false,
                        confirmButtonText: '保 存',
                        cancelButtonText: '不保存',
                    }).then(() => {
                        this.sendEmail(2)
                    }).catch(() => {
                    })
                }
            })
            let content = this.$route.query.content;
            if (content) {
                this.$refs.makeBtn.insertEditor(content)
            }
            //来自客户
            let customer = this.$route.query.customer;
            if (customer) {
                let res;
                if (customer.indexOf(',')) {
                    res = customer.split(',');
                } else {
                    res = [customer]
                }
                let emailSubject;
                if (this.$route.query.emailSubject) {
                    this.form.emailOriginalId = this.$route.query.emailOriginalId;
                    emailSubject = this.$route.query.emailSubject;
                }
                if (this.$route.query.emailContent) {
                    this.$refs.makeBtn.initContent(this.$route.query.emailContent);
                } else {
                    this.$refs.makeBtn.initContent(`${this.common.sign}`);
                }
                this.$refs.write.customerInit(res, emailSubject);
                this.$refs.write.initSend(this.$route.query.senderEmail);
            }
            //来自订单
            let file = this.$route.query.file;
            if (file) {
                this.$refs.makeBtn.initFile([file]);
            }
            if (this.content) {//编辑
                const detail = JSON.parse(this.content);
                this.form.emailContent = detail.emailContent;
                this.form.emailSubject = detail.emailSubject;
                this.form.addresseeEmail = dealStr(detail.addresseeEmail);
                this.form.emailCarbonCopy = dealStr(detail.emailCarbonCopy);
                this.form.emailSecretDelivery = dealStr(detail.emailSecretDelivery);
                this.form.emailHtmlpicList = detail.emailHtmlpicList;
                this.form.emailReceipt = parseInt(detail.emailReceipt);
                this.form.emaileDelivery = parseInt(detail.emaileDelivery);
                if (this.form.monocular == 1) this.checkList.push('群发单显');
                if (this.form.emailReceipt == 1) this.checkList.push('回执');
                if (this.form.emaileDelivery == 2) this.checkList.push('紧急');
                if (this.form.emailTrack == 1) {
                    this.checkList.push('追踪邮件')
                } else {
                    this.checkList.splice(this.checkList.findIndex(item => item == '追踪邮件'), 1)
                }
                this.form.senderNickName = detail.senderNickName;
                this.form.senderEmail = detail.senderEmail;
                this.$refs.childEdit.getInit(detail.emailContent);
            } else {
                let email = this.common.currentEmail;
                if (email == '') { //全部邮箱时候 - 选择默认的
                    this.common.emailList.map(item => {
                        if (item.isDefault) {
                            this.form.senderEmail = item.emailAddr;
                            return;
                        }
                    })
                } else {
                    this.form.senderEmail = email;
                }
                this.form.senderNickName = this.userInfo.account;//获取用户名
                this.$refs.write.initSend(this.form.senderEmail);
            }
            if (this.$route.fullPath == '/mail/write/index') {//写信时候才会存在
                this.$refs.makeBtn.initContent(`${this.common.sign}`);
            }
            //来自作为附件发送
            let info = this.$route.query.info;
            if (info) {
                info = JSON.parse(info);
                //初始化附件
                this.$refs.makeBtn.initFile(info.emailHtmlpicList)
                //初始化主题
                this.$refs.write.initSubject(info.emailSubject);
            }
            this.isEnd = true;
        },
        methods: {
            //取消按钮回调
            getCancel(params) {
                this.form = Object.assign({}, this.form, params);
                if (this.form.addresseeEmail.length != 0 && this.form.emailSubject != '' && (this.form.senderEmail != '') && !this.common.isExpired) {
                    this.$confirm(' <div style="margin: 20px 10px;">\n' +
                        '        <p style="line-height: 30px;\n' +
                        '        font-size: 14px;">您正在编辑内容，是否保存至草稿箱？</p>\n' +
                        '      </div>', '保存邮件到草稿箱', {
                        dangerouslyUseHTMLString: true,
                        closeOnClickModal: false,
                        closeOnPressEscape: false,
                        confirmButtonText: '保 存',
                        cancelButtonText: '不保存',
                    }).then(() => {
                        this.sendEmail(this.form.sendType)
                        this.backHistory();
                    }).catch(() => {
                        this.backHistory();
                    })
                } else {
                    this.backHistory();
                }
            },
            backHistory() {
                if (this.$route.query.where) {
                    this.$router.go(-1)
                } else {
                    this.$router.push('/mail/index')
                }
            },
            getInfoMake(params) {
                this.form = Object.assign({}, this.form, params)
            },
            getInfoWrite(params) { //顶部数据 - 点击发送按钮触发
                this.form = Object.assign({}, this.form, params);
                this.sendEmail(params.sendType)
            },
            getSendEmail(email) {
                this.form.senderEmail = email;
            },
            //预览
            review(params) {
                let info = Object.assign({}, this.form, params);
                let routeUrl = this.$router.resolve({
                    name: '/mail/write/Review',
                    query: {
                        info: JSON.stringify(info)
                    }
                });
                window.open(routeUrl.href, '_blank');
            },
            cancel() {
                this.$confirm('您正在写信，是否离开写信页面?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "success"
                }).then(() => {
                    this.$router.go(-1)
                }).catch(() => {
                    return;
                });
            },
            //提交审批
            toApproval(params) {
                this.form.emailReceipt = this.form.emaileDelivery = 0;
                this.checkList.map(item => {
                    if (item === '回执') {
                        this.form.emailReceipt = 1;
                    } else if (item === '紧急') {
                        this.form.emaileDelivery = 2;
                    } else if (item === '追踪邮件') {
                        this.form.emailTrack = 1;
                    }
                })
                this.form = Object.assign({}, this.form, params);
                if (this.getParams()) {
                    const target = JSON.parse(JSON.stringify(this.form));
                    this.$refs.dialogApproval.init(target);
                }
            },
            getParams() {
                if (this.form.senderEmail == '') {
                    this.$message({
                        duration: 1500,
                        message: '请选择发件人邮箱',
                        type: "success"
                    });
                    return false
                } else if (this.form.addresseeEmail.length === 0) {
                    this.$message({
                        duration: 1500,
                        message: '请输入收件人邮箱',
                        type: "success"
                    });
                    return false
                } else if (!this.form.emailSubject) {
                    this.$message({
                        duration: 1500,
                        message: '请输入主题',
                        type: "success"
                    });
                    return false
                } else if (!this.form.emailContent) {
                    this.$message({
                        duration: 1500,
                        message: '请输入邮件内容',
                        type: "success"
                    });
                    return false
                } else {
                    return true
                }
            },
            //发送邮件
            sendEmail(type) {
                if (this.form.senderEmail == '') {
                    this.$message({
                        duration: 1500,
                        message: '请选择发件人邮箱',
                        type: "success"
                    });
                    return;
                } else if (this.form.addresseeEmail.length === 0) {
                    this.$message({
                        duration: 1500,
                        message: '请输入收件人邮箱',
                        type: "success"
                    });
                    return;
                }
                if (type != 2) {
                    if (!this.form.emailSubject) {
                        this.$message({
                            duration: 1500,
                            message: '请输入主题',
                            type: "success"
                        });
                        return;
                    }
                }
                //判断群发单线个数  30
                let msg = '';
                if (this.form.emailSecretDelivery.length > 20) {
                    msg = '密送人最多不超过20个！'
                }
                if (this.form.emailCarbonCopy.length > 20) {
                    msg = '抄送人最多不超过20个！'
                }
                if (this.form.addresseeEmail.length > 30) {
                    msg = '收件人最多不超过30个！'
                }
                if (msg) {
                    this.$confirm(' <div style="margin: 20px 10px;">\n' +
                        '        <p style="line-height: 30px;font-size: 14px;">' + msg + '</p></div>', '提示', {
                        dangerouslyUseHTMLString: true,
                        closeOnClickModal: false,
                        closeOnPressEscape: false,
                        confirmButtonText: '确 定',
                    }).then(() => {
                        return;
                    }).catch(() => {
                        return;
                    })
                }
                //处理参数
                this.form.emailReceipt = this.form.emaileDelivery = 0;
                let state = true;
                this.checkList.map(item => {
                    if (item === '回执') {
                        this.form.emailReceipt = 1;
                    } else if (item === '紧急') {
                        this.form.emaileDelivery = 2;
                    } else if (item === '追踪邮件') {
                        this.form.emailTrack = 1;
                    } else if (item === '定时发送') {
                        if (this.form.emailSendTiming == '') {
                            state = false;
                            this.$message({
                                duration: 1500,
                                message: '请选择定时发送时间',
                                type: "success"
                            });
                        }
                    }
                })
                if (!state) {
                    return;
                }
                this.form.emailContent = encodeURIComponent(this.form.emailContent);
                this.form.boxId = type ? type : '';
                this.toSend();
            },
            toSend() {
                if (this.content) {//编辑
                    this.form = Object.assign({}, this.form, {temailInfoId: JSON.parse(this.content).temailInfoId})
                }
                const boxID = this.form.boxId;
                const title = this.form.emailSubject;
                const monocular = this.form.monocular;
                const emailSendTiming = this.form.emailSendTiming;
                this.isLoading = true;
                sendEmail(this.form).then(res => {
                    this.isLoading = false;
                    if (res.data.success) {
                        this.reset();
                        this.bus.$emit('refreshEmailNum')
                        if (boxID == 2) {//存草稿
                            this.$message({message: res.data.msg, type: 'success'});
                        } else {
                            //跳转 成功页面
                            const params = JSON.stringify({
                                    id: res.data.data,
                                    title: title,
                                    monocular: monocular,
                                    emailSendTiming: emailSendTiming
                                })
                            this.$router.push({
                                path: '/mail/success',
                                query: {
                                    params: params
                                }
                            });
                        }
                    } else {
                        this.form.emailContent = decodeURIComponent(this.form.emailContent);
                    }
                }).catch(err => {
                    this.isLoading = false;
                    this.form.emailContent = decodeURIComponent(this.form.emailContent);//防止二次提交
                })
            },
            //重置数据
            reset() {
                this.$refs.write.init()//重置顶部组件
                this.$refs.makeBtn.init();//重置编辑器
                this.form = {
                    addresseeEmail: [],//收件人邮箱数组
                    emailCarbonCopy: [],//抄送数组
                    emailSecretDelivery: [],//密送数组
                    emailHtmlpicList: [],//附件列表
                    emailSubject: '',//主题
                    emailContent: '',//邮件内容
                    emailReceipt: 0,//是否回执 0-默认不回执，1-回执
                    emaileDelivery: 0,//投递状态  （紧急与非紧急） 0-默认常规，2-紧急
                    senderEmail: '',//发件人邮箱
                    senderNickName: this.userInfo.account,//发件人昵称,
                    emailSendTiming: '',
                    boxId: ''
                }
                this.checkList = [];
            },
            getRightTime(time) {//回调时间
                this.form.emailSendTiming = time;
                if (time == '') {
                    const index = this.checkList.indexOf("定时发送");
                    this.checkList.splice(index, 1);
                }
            },
            getArrDifference(arr1, arr2) {
                return arr1.concat(arr2).filter(function (v, i, arr) {
                    return arr.indexOf(v) === arr.lastIndexOf(v);
                });
            }
        }
    }
</script>

<style lang="scss">
  $bgActiveColor: #E9F3FD;
  $fontColor: #2A97F9;
  $lineColor: #F3F3F3;
  .write {
    height: 100%;
    overflow-y: auto;

    button.el-button.el-button--default {
      line-height: 30px;
      padding: 0 15px;

      i {
        margin-right: 5px;
      }
    }

    button.el-button.el-button--default.active {
      background-color: $bgActiveColor;
      color: $fontColor;
    }

    .info {
      margin: 15px 0;
      display: flex;
      align-items: center;

      h1 {
        font-size: 14px;
        color: #1B2242;
        margin-right: 30px;
      }
    }

    .make-btn {
      margin-bottom: 15px;
    }
  }
</style>


